package com.nanyang.tms.manager.company.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.nanyang.common.core.annotation.SystemLog;
import com.nanyang.common.core.dict.CommonEnum;
import com.nanyang.common.core.domain.ApiResult;
import com.nanyang.common.core.page.PageBean;
import com.nanyang.common.core.page.PageTableBean;
import com.nanyang.common.tool.utils.convert.BeanUtils;
import com.nanyang.common.tool.utils.uuid.GlobalIdGeneratorUtil;
import com.nanyang.sys.api.dto.request.login.OperateUserAccountRequest;
import com.nanyang.sys.api.dto.request.login.UserAddRequest;
import com.nanyang.sys.api.dto.request.obsauth.ObsAuthGetFilePathRequest;
import com.nanyang.sys.api.dto.response.obsauth.ObsAuthGetFilePathResponse;
import com.nanyang.sys.api.service.login.UserRpcService;
import com.nanyang.sys.api.service.obsauth.ObsAuthRpcService;
import com.nanyang.tms.common.config.TmsConfig;
import com.nanyang.tms.common.contstant.TmsSerializeConstant;
import com.nanyang.tms.common.dict.TmsCommonEnum;
import com.nanyang.tms.common.dict.TmsExceptionEnum;
import com.nanyang.tms.common.exception.TmsManagerException;
import com.nanyang.tms.common.util.RpcCheckUtils;
import com.nanyang.tms.common.util.TmsExceptionUtil;
import com.nanyang.tms.dao.company.CompanyDao;
import com.nanyang.tms.dao.company.CompanyStoredDao;
import com.nanyang.tms.dao.company.CompanyUserDao;
import com.nanyang.tms.domain.company.*;
import com.nanyang.tms.manager.company.CompanyManager;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component("companyManager")
public class CompanyManagerImpl implements CompanyManager {
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private CompanyUserDao companyUserDao;
    @Autowired
    private GlobalIdGeneratorUtil globalIdGeneratorUtil;
    @Autowired
    private CompanyStoredDao companyStoredDao;
    @Autowired
    private TmsConfig tmsConfig;
    @Reference(version = "1.0.0", timeout = 10000, check = false)
    private ObsAuthRpcService obsAuthRpcService;

    @Reference(version = "1.0.0", timeout = 10000, check = false)
    private UserRpcService userRpcService;
    @Override
    public PageBean<CompanyVO> listCompany(CompanyQuery query) {
        try {
            if (query == null) {
                log.error(TmsCommonEnum.PARAM_IS_NULL.getCode() + TmsCommonEnum.PARAM_IS_NULL.getMessage());
                throw new TmsManagerException(TmsCommonEnum.PARAM_IS_NULL.getCode() ,TmsCommonEnum.PARAM_IS_NULL.getMessage());
            }
            Integer count = companyDao.countCompany(query);
            PageBean<CompanyVO> page = new PageTableBean<CompanyVO>(query.getPageIndex(), query.getPageSize());
            if (null != count && count != 0) {
                page.setTotalItem(count);
                int startRow = page.getStartRow();
                if (startRow > 0) {
                    startRow -= 1;
                }
                query.setStartRow(startRow);
                page.addAll(companyDao.listCompany(query));
            }
            return page;
        } catch (Exception e) {
            throw TmsExceptionUtil.wrapException(e);
        }
    }
    @SystemLog(module =SystemLog.Module.COMPANY,template="companyAdd")
    @Override
    @Transactional
    public void saveCompany(CompanyVO companyVO) {
        try {
            CompanyQuery companyQuery = new CompanyQuery();
            companyQuery.setCompanyName(companyVO.getCompanyName());
            int comcount = companyDao.queryVerifyCompanyName(companyQuery);
            if(comcount>0){
                throw new TmsManagerException(TmsExceptionEnum.PARAM_COMPANYNAME_EXIST.getCode() ,TmsExceptionEnum.PARAM_COMPANYNAME_EXIST.getMessage());
            }

            CompanyDO companyDO=new CompanyDO();
            BeanUtils.copyProperties(companyVO,companyDO);
            String companyCode = TmsSerializeConstant.COMPANY_KEY+globalIdGeneratorUtil.getNextSeq(TmsSerializeConstant.COMPANY_SEQ_KEY, TmsSerializeConstant.SEQ_INCRBY);
            companyDO.setCompanyCode(companyCode);
            companyDO.setCompanyAuthUrl(getUrl(companyVO.getCompanyAuthUrl()));
            companyDO.setIdNurl(getUrl(companyVO.getIdNurl()));
            companyDO.setIdPurl(getUrl(companyVO.getIdPurl()));
            companyDO.setLevelCode("VIP0");
            companyDO.setLevelName("普通会员");
            companyDao.insert(companyDO);
            int count = companyUserDao.queryCountByMobile(companyVO.getMobile());
            if(count>0){
                throw new TmsManagerException(TmsExceptionEnum.PARAM_MOBILE_EXIST.getCode() ,TmsExceptionEnum.PARAM_MOBILE_EXIST.getMessage());
            }
            CompanyUserDO companyUserDO = new CompanyUserDO();
            BeanUtils.copyProperties(companyVO,companyUserDO);
            String pin = globalIdGeneratorUtil.getNextSeq(TmsSerializeConstant.COMPANYUSER_SEQ_KEY, TmsSerializeConstant.SEQ_INCRBY);
            companyUserDO.setPin(pin);
            companyUserDO.setUserName(companyVO.getMobile());
            companyUserDO.setCompanyCode(companyCode);
            companyUserDao.insert(companyUserDO);
        } catch (TmsManagerException e) {
            throw TmsExceptionUtil.wrapException(e);
        }
    }

    private String getUrl(String url) throws TmsManagerException{
        ObsAuthGetFilePathRequest request=new ObsAuthGetFilePathRequest();
        request.setSignUrl(url);
        ApiResult<ObsAuthGetFilePathResponse> filePathBySignUrl = obsAuthRpcService.getFilePathBySignUrl(request);
        if(RpcCheckUtils.isRpcInvokeError(filePathBySignUrl)){
            throw new TmsManagerException(TmsExceptionEnum.SIGN_URL_FAIL.getCode(),TmsExceptionEnum.SIGN_URL_FAIL.getMessage());
        }
        return filePathBySignUrl.getData().getFilePath();
    }
    @SystemLog(module =SystemLog.Module.COMPANY,template="companyUpdate")
    @Override
    public void updateCompany(CompanyDO companyDO) {
        try {
            CompanyQuery companyQuery = new  CompanyQuery();
            companyQuery.setCompanyName(companyDO.getCompanyName());
            companyQuery.setCompanyCode(companyDO.getCompanyCode());
            if (companyDao.queryVerifyCompanyName(companyQuery) > 0) {
                throw new TmsManagerException(TmsExceptionEnum.PARAM_COMPANYNAME_EXIST.getCode(),TmsExceptionEnum.PARAM_COMPANYNAME_EXIST.getMessage());
            }
            companyDao.update(companyDO);
        } catch (TmsManagerException e) {
            throw TmsExceptionUtil.wrapException(e);
        }
    }
    @Override
    @GlobalTransactional
    public void disableState(CompanyDO companyDO){
        CompanyUserVO companyUserVO = companyUserDao.selectByCode(companyDO.getCompanyCode());
        if(ObjectUtil.isNull(companyUserVO)){
            throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
        }
        if(companyDao.disableState(companyDO)<=0){
            throw new TmsManagerException(TmsExceptionEnum.COMPANY_STATE_ERROR.getCode(),TmsExceptionEnum.COMPANY_STATE_ERROR.getMessage());
        };
        OperateUserAccountRequest operateUserAccountRequest=new OperateUserAccountRequest();
        operateUserAccountRequest.setDisabled(1);
        operateUserAccountRequest.setPin(companyDO.getGmtModifiedPin());
        List<String> list = new ArrayList<>();
        list.add(companyUserVO.getPin());
        operateUserAccountRequest.setUserPinList(list);
        ApiResult<Boolean> apiResult = userRpcService.enableOrDisableUserAccount(operateUserAccountRequest);
        if(RpcCheckUtils.isRpcInvokeError(apiResult)){
            log.error("设置用户信息失败：入参{},返回{}", JSONUtil.toJsonStr(operateUserAccountRequest),JSONUtil.toJsonStr(apiResult));
            throw new TmsManagerException(TmsExceptionEnum.SAVE_USER_ERROR.getCode(),TmsExceptionEnum.SAVE_USER_ERROR.getMessage());
        }
    }
    @Override
    @GlobalTransactional
    public void enableState(CompanyDO companyDO){
        CompanyUserVO companyUserVO = companyUserDao.selectByCode(companyDO.getCompanyCode());
        if(ObjectUtil.isNull(companyUserVO)){
            throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
        }
        if(companyDao.enableState(companyDO)<=0){
            throw new TmsManagerException(TmsExceptionEnum.COMPANY_STATE_ERROR.getCode(),TmsExceptionEnum.COMPANY_STATE_ERROR.getMessage());
        };
        OperateUserAccountRequest operateUserAccountRequest=new OperateUserAccountRequest();
        operateUserAccountRequest.setDisabled(0);
        operateUserAccountRequest.setPin(companyDO.getGmtModifiedPin());
        List<String> list = new ArrayList<>();
        list.add(companyUserVO.getPin());
        operateUserAccountRequest.setUserPinList(list);
        ApiResult<Boolean> apiResult = userRpcService.enableOrDisableUserAccount(operateUserAccountRequest);
        if(RpcCheckUtils.isRpcInvokeError(apiResult)){
            log.error("设置用户信息失败：入参{},返回{}", JSONUtil.toJsonStr(operateUserAccountRequest),JSONUtil.toJsonStr(apiResult));
            throw new TmsManagerException(TmsExceptionEnum.SAVE_USER_ERROR.getCode(),TmsExceptionEnum.SAVE_USER_ERROR.getMessage());
        }
    }
    @Override
    @GlobalTransactional
    public void passState(CompanyDO companyDO) {
        try {
            CompanyUserVO companyUserVO = companyUserDao.selectByCode(companyDO.getCompanyCode());
            if(ObjectUtil.isNull(companyUserVO)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            if(companyDao.passState(companyDO)<=0){
                throw new TmsManagerException(TmsExceptionEnum.COMPANY_STATE_ERROR.getCode(),TmsExceptionEnum.COMPANY_STATE_ERROR.getMessage());
            };
            CompanyStoredDO companyStoredDO = new CompanyStoredDO();
            companyStoredDO.setCompanyCode(companyUserVO.getCompanyCode());
            companyStoredDO.setCompanyName(companyDao.selectByCode(companyUserVO.getCompanyCode()).getCompanyName());
            companyStoredDO.setPin(companyUserVO.getPin());
            companyStoredDO.setUserName(companyUserVO.getUserName());
            String cardNo = globalIdGeneratorUtil.getNextSeq(TmsSerializeConstant.COMPANYSTORE_SEQ_KEY, TmsSerializeConstant.SEQ_INCRBY);
            companyStoredDO.setCardNo("CN"+cardNo);
            companyStoredDO.setCardName(tmsConfig.getCardName());
            companyStoredDO.setGmtCreatePin(companyDO.getGmtModifiedPin());
            companyStoredDO.setIp(companyUserVO.getIp());
            companyStoredDao.insert(companyStoredDO);

            UserAddRequest userAddRequest=new UserAddRequest();
            BeanUtils.copyProperties(companyUserVO,userAddRequest);
            ApiResult<Boolean> apiResult = userRpcService.userRegister(userAddRequest);
            if(RpcCheckUtils.isRpcInvokeError(apiResult)){
                log.error("保存用户信息失败：入参{},返回{}", JSONUtil.toJsonStr(userAddRequest),JSONUtil.toJsonStr(apiResult));
                throw new TmsManagerException(TmsExceptionEnum.SAVE_USER_ERROR.getCode(),TmsExceptionEnum.SAVE_USER_ERROR.getMessage());
            }
        } catch (TmsManagerException e) {
            throw TmsExceptionUtil.wrapException(e);
        }
    }
}
